package com.yanqu.road.entity.activity.suitang.config;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangWarType;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangStage;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class SuiTangConfigSync {
    // 活动ID
    private int activityId;

    // 活动信息
    private ActivityInfo activityInfo;

    // 活动配置信息
    private Map<String, ActivityConfig> activityConfigMap;

    // 城市配置
    private Map<Integer, SuiTangCityConfig> cityConfigMap;

    // 城市类型配置
    private Map<Integer, SuiTangCityTypeConfig> cityTypeConfigMap;

    // buff 配置
    private Map<Integer, SuiTangBuffConfig> buffConfigMap;

    // param 配置
    private SuiTangParamConfig paramConfig = new SuiTangParamConfig();

    // rank 配置
    private Map<Integer, SuiTangRankConfig> rankConfigMap;

    // guess 配置
    private Map<Integer, SuiTangGuessConfig> guessConfigMap;

    // 地图
    private Map<Integer, List<Integer>> cityConnectMap;                                     // 城池连接，Map<城池ID，相邻城池ID>

    private static final Logger logger = LogManager.getLogger(SuiTangConfigSync.class.getName());

    // 阵营礼包
    private Map<Integer, SuiTangCampBoxConfig> campBoxConfigMap = new ConcurrentHashMap<>();                           // 阵营宝箱

    // 构造函数
    public SuiTangConfigSync(
            ActivityInfo activityInfo,
            Map<String, ActivityConfig> activityConfigMap,
            Map<Integer, SuiTangCityConfig> cityConfigMap,
            Map<Integer, SuiTangCityTypeConfig> cityTypeConfigMap,
            Map<Integer, SuiTangBuffConfig> buffConfigMap,
            Map<Integer, SuiTangRankConfig> rankConfigMap
    ) {
        if (activityInfo == null) {
            return;
        }
        this.activityId = activityInfo.getActivityId();
        this.activityInfo = activityInfo;
        this.activityConfigMap = activityConfigMap;
        this.cityConfigMap = cityConfigMap;
        this.cityTypeConfigMap = cityTypeConfigMap;
        this.buffConfigMap = buffConfigMap;
        this.rankConfigMap = rankConfigMap;

        if (!paramConfig.initParamConfig(activityConfigMap)) {
            logger.error("配置初始化错误，配置名：{}，活动ID：{}，",
                    SuiTangParamConfig.class.getName(),
                    activityId
            );
        }

        for (Map.Entry<Integer, SuiTangCityTypeConfig> entry : cityTypeConfigMap.entrySet()) {
            if (entry == null) {
                continue;
            }
            SuiTangCityTypeConfig cityTypeConfig = entry.getValue();
            if (cityTypeConfig == null || !entry.getValue().InitParamConfig()) {
                logger.error("配置初始化错误，配置名：{}，活动ID：{}，",
                        SuiTangCityTypeConfig.class.getName(),
                        activityId
                );
            }
        }
    }

    // 构造函数
    public SuiTangConfigSync() {}

    public void calcCampBoxConfig() {
        for (List<Long> list : paramConfig.getSuiTangCampGiftBag()) {
            SuiTangCampBoxConfig campBoxConfig = new SuiTangCampBoxConfig();
            campBoxConfig.setKey(list.get(0).intValue());
            campBoxConfig.setBoxId(list.get(1).intValue());
            campBoxConfig.setBoxScore(list.get(2).intValue());
            campBoxConfigMap.put(campBoxConfig.getKey(), campBoxConfig);
        }
    }

    public Map<Integer, SuiTangCampBoxConfig> getCampBoxConfigMap() {
        return campBoxConfigMap;
    }

    public void setCampBoxConfigMap(Map<Integer, SuiTangCampBoxConfig> campBoxConfigMap) {
        this.campBoxConfigMap = campBoxConfigMap;
    }

    public int getActivityId() {
        return activityId;
    }

    public void setActivityId(int activityId) {
        this.activityId = activityId;
    }

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void setActivityInfo(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public Map<String, ActivityConfig> getActivityConfigMap() {
        return activityConfigMap;
    }

    public void setActivityConfigMap(Map<String, ActivityConfig> activityConfigMap) {
        this.activityConfigMap = activityConfigMap;
    }

    public Map<Integer, SuiTangCityConfig> getCityConfigMap() {
        return cityConfigMap;
    }

    public void setCityConfigMap(Map<Integer, SuiTangCityConfig> cityConfigMap) {
        this.cityConfigMap = cityConfigMap;
    }

    public Map<Integer, SuiTangCityTypeConfig> getCityTypeConfigMap() {
        return cityTypeConfigMap;
    }

    public int getCityTypeConfigKey(eSuiTangWarType warType, int cityType) {
        return warType.getType() * 10 + cityType;
    }

    public void setCityTypeConfigMap(Map<Integer, SuiTangCityTypeConfig> cityTypeConfigMap) {
        this.cityTypeConfigMap = cityTypeConfigMap;
    }

    public Map<Integer, SuiTangBuffConfig> getBuffConfigMap() {
        return buffConfigMap;
    }

    public void setBuffConfigMap(Map<Integer, SuiTangBuffConfig> buffConfigMap) {
        this.buffConfigMap = buffConfigMap;
    }

    public SuiTangParamConfig getParamConfig() {
        return paramConfig;
    }

    public void setParamConfig(SuiTangParamConfig paramConfig) {
        this.paramConfig = paramConfig;
    }

    public Map<Integer, SuiTangRankConfig> getRankConfigMap() {
        return rankConfigMap;
    }

    public void setRankConfigMap(Map<Integer, SuiTangRankConfig> rankConfigMap) {
        this.rankConfigMap = rankConfigMap;
    }

    public Map<Integer, List<Integer>> getCityConnectMap() {
        return cityConnectMap;
    }

    public void setCityConnectMap(Map<Integer, List<Integer>> cityConnectMap) {
        this.cityConnectMap = cityConnectMap;
    }

    public Map<Integer, SuiTangGuessConfig> getGuessConfigMap() {
        return guessConfigMap;
    }

    public void setGuessConfigMap(Map<Integer, SuiTangGuessConfig> guessConfigMap) {
        this.guessConfigMap = guessConfigMap;
    }

    public List<Long> getJoinTimeList() {
        if (joinTimeList.isEmpty()) {
            calcTimeList();
        }
        return joinTimeList;
    }

    public List<List<Long>> getStage1TimeList() {
        if (stage1TimeList.isEmpty()) {
            calcTimeList();
        }
        return stage1TimeList;
    }

    // 时间
    private List<Long> joinTimeList = new ArrayList<>();                                                        // 报名时间    [开始时间，结束时间]
    private List<List<Long>> stage1TimeList = new ArrayList<>();                                                // 第一阶段时间    [开始时间，结束时间] , [开始时间，结束时间] , ...
    public void calcTimeList() {
        joinTimeList.add(activityInfo.getBeginTime() * DateHelper.SECOND_MILLIONS +
                (getParamConfig().getSuiTangCreateTeamTime().get(0) - 1) * DateHelper.DAY_MILLIONS + getParamConfig().getSuiTangCreateTeamTime().get(1) * DateHelper.HOUR_MILLIONS);
        joinTimeList.add(activityInfo.getBeginTime() * DateHelper.SECOND_MILLIONS +
                (getParamConfig().getSuiTangCreateTeamTime().get(0) - 1) * DateHelper.DAY_MILLIONS + getParamConfig().getSuiTangCreateTeamTime().get(2) * DateHelper.HOUR_MILLIONS);
        for (List<Long> list : getParamConfig().getSuiTangFirstStageTime()) {
            List<Long> tempList = new ArrayList<>();
            tempList.add(activityInfo.getBeginTime() * DateHelper.SECOND_MILLIONS +
                    (list.get(0) - 1) * DateHelper.DAY_MILLIONS + list.get(1) * DateHelper.HOUR_MILLIONS);
            tempList.add(activityInfo.getBeginTime() * DateHelper.SECOND_MILLIONS +
                    (list.get(0) - 1) * DateHelper.DAY_MILLIONS + list.get(2) * DateHelper.HOUR_MILLIONS);
            stage1TimeList.add(tempList);
        }
    }

    /**
     * 进入活动页面的时间内
     */
    public boolean inEnterActivityTime() {
        long now = System.currentTimeMillis();
        if (stage1TimeList.isEmpty()) {
            calcTimeList();
        }
        return now >= stage1TimeList.get(0).get(0) && now < activityInfo.getEndTime() * 1000L;
    }
    
    /*
     * 22点-0点的休战期
     */
    public boolean inTodayRestTime() {
        return DateHelper.getHours() >= DateHelper.getTimeStampHours(stage1TimeList.get(0).get(1));
    }

    /**
     * 准备期
     */
    public boolean inReadyTime() {
        return getSuiTangStage().getValue() == eSuiTangStage.ReadyTime.getValue();
    }

    /*
     * 获取当前轮次的活动开始时间
     */
    public long getRoundBeginTime(int round) {
        return stage1TimeList.get(round - 1).get(0);
    }

    /**
     * 获取当前阶段
     */
    public eSuiTangStage getSuiTangStage() {
        long now = System.currentTimeMillis();
        if (joinTimeList.isEmpty()) {
            calcTimeList();
        }

        if (now < joinTimeList.get(0)) {
            return eSuiTangStage.NoStart;
        }
        if (now < joinTimeList.get(1)) {
            return eSuiTangStage.JoinTime;
        }
        if (now < stage1TimeList.get(0).get(0)) {
            return eSuiTangStage.ReadyTime;
        }
        if (now < stage1TimeList.get(stage1TimeList.size() - 1).get(1)) {
            for (List<Long> list : stage1TimeList) {
                if (now >= list.get(0) && now < list.get(1)) {
                    return eSuiTangStage.Stage1Time;
                }
            }
            return eSuiTangStage.Stage1RestTime;
        }
        if (now < activityInfo.getEndTime() * 1000L) {
            return eSuiTangStage.Stage1EndTime;
        }
        if (now < activityInfo.getEndTime() * 1000L + DateHelper.MINUTE_MILLIONS * 5) {
            return eSuiTangStage.WaitRewardTime;
        }
        if (now < activityInfo.getEndShowTime() * 1000L) {
            return eSuiTangStage.RewardTime;
        }
        return eSuiTangStage.ActivityEndShow;
    }

    public int getRankScore(int round, int warType, int rank) {
        for (SuiTangRankConfig value : getRankConfigMap().values()) {
            if (value.getRound() == round && value.getWarType() == warType && value.getRank() >= rank) {
                return value.getRewards();
            }
        }
        return 0;
    }

    /*
     * 请求接口的时间限制
     */
    public boolean isRequestTime() {
        long stage1BeginTime = getStage1TimeList().get(0).get(0);
        long zeroTimeStamp = DateHelper.getZeroTimeStamp(stage1BeginTime) + 10 * DateHelper.MINUTE_MILLIONS;
        long now = System.currentTimeMillis();
        if (now < zeroTimeStamp) {
            return false;
        }
        return true;
    }

    /*
     * 操作接口的时间限制
     */
    public boolean isOperateTime() {
        long stage1BeginTime = getStage1TimeList().get(0).get(0);
        long zeroTimeStamp = DateHelper.getZeroTimeStamp(stage1BeginTime) + 10 * DateHelper.MINUTE_MILLIONS;
        long now = System.currentTimeMillis();
        if (now < zeroTimeStamp || now > getStage1TimeList().get(getStage1TimeList().size() - 1).get(1)) {
            return false;
        }
        return true;
    }

    public int getCityScoreToRankScore(int round, int warType, long currentCityScore) {
        ActivityConfig activityConfig = activityConfigMap.get("SUITANG_SHILI_SCORE");
        if (activityConfig == null) {
            return 0;
        }

        if (currentCityScore <= 0) {
            return 0;
        }

        int translateRate = 0;//转化率
        String[] split = activityConfig.getValue().split("\\|");
        for (int i = 0; i < split.length; i++) {
            if (i + 1 == round) {
                List<Integer> list = StringUtils.stringToIntegerList(split[i], ";");
                for (int i1 = 0; i1 < list.size(); i1++) {
                    if (i1 + 1 == warType) {
                        translateRate = list.get(i1);
                        break;
                    }
                }
            }
        }
        if (translateRate <= 0) {
            return 0;
        }
        int result = BigDecimal.valueOf(translateRate).divide(BigDecimal.valueOf(1000)).multiply(BigDecimal.valueOf(currentCityScore)).setScale(0, BigDecimal.ROUND_UP).intValue();
        return result;
    }

    /**
     * 获取隋唐晋级奖励
     *
     * @return
     */
    public Property getPromotRewards(int round, eSuiTangWarType warType) {
        ActivityConfig activityConfig = activityConfigMap.get("SUITANG_GROUP_PROMOT_REWARDS");
        if (activityConfig == null) {
            return null;
        }
        List<String> list = StringUtils.stringToStringList(activityConfig.getValue(), "\\|");
        // 第一天义军→骁骑|第二天义军→骁骑|第二天骁骑→禁军
        // 第二天骁骑|第三天骁骑|第三天禁军
        // 直接枚举吧就三个，写循环理不清了
        if (round == 2 && warType == eSuiTangWarType.WAR_TYPE_XIAOQI) {
            return PropertyHelper.parseStringToProperty(list.get(0));
        } else if (round == 3 && warType == eSuiTangWarType.WAR_TYPE_XIAOQI) {
            return PropertyHelper.parseStringToProperty(list.get(1));
        } else if (round == 3 && warType == eSuiTangWarType.WAR_TYPE_JINJUN) {
            return PropertyHelper.parseStringToProperty(list.get(2));
        }
        return null;

    }
}
